/*
 * usart.c
 *
 * Created: 05.09.2012 16:06:06
 *  Author: bardbakk
 */

#define F_CPU 8500000
#include "USART.h"
#include <avr/io.h> 
#include <avr/interrupt.h>
#include <stdio.h>

void USART_init(unsigned int baudrate){
	
	unsigned int baud;
	baud = ((F_CPU)/(16UL*baudrate)) - 1;
	
	cli();
	UBRR1H = (unsigned char)(baud>>8);
	UBRR1L = (unsigned char)baud;
	
	//Enables receive, transmit and receive interrupt
	UCSR1B = (1<<RXEN1)|(1<<TXEN1)/*|(1<<RXCIE0)*/;
	
	//Enables use of UCSRC and sets frame format: 2 stop bits, 8 bits. 
	UCSR1C = (1<<USBS1)|(3<<UCSZ10);
		
	sei();
	
	fdevopen(USART_transmit, USART_receive);
}

void USART_transmit(unsigned char data)
{
	while(!(UCSR1A & (1<<UDRE1)))
	{
	}
	UDR1=data;
	return 0;
}

unsigned char USART_receive()
{
	char receivedByte = UDR1;
	return receivedByte;
}



ISR(USART1_RXC_vect, ISR_BLOCK)
{
	char receivedByte = USART_receive();
	USART_transmit(receivedByte);
}